package org.example.websocket1.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationListener;
import org.springframework.messaging.simp.SimpMessagingTemplate;
import org.springframework.messaging.simp.stomp.StompHeaderAccessor;
import org.springframework.security.core.session.SessionRegistry;
import org.springframework.security.core.userdetails.User;
import org.springframework.stereotype.Service;
import org.springframework.web.socket.messaging.SessionDisconnectEvent;

import java.security.Principal;
import java.util.ArrayList;
import java.util.List;

@Service
public class StompDisconnectEventListener implements ApplicationListener<SessionDisconnectEvent> {
    @Autowired
    private SimpMessagingTemplate messagingTemplate;

    @Autowired
    SessionRegistry sessionRegistry;

    @Override
    public void onApplicationEvent(SessionDisconnectEvent event) {
        StompHeaderAccessor sha = StompHeaderAccessor.wrap(event.getMessage());
        Principal principal = sha.getUser();
        List<Object> list = sessionRegistry.getAllPrincipals();
        List<String> users = new ArrayList<>();
        for(Object o:list){
            User u = (User) o;
            if(u.getUsername().equals(principal.getName())){
                continue;
            }
            users.add(u.getUsername());
        }
        messagingTemplate.convertAndSend("/topic/receiveAll", users);
    }
}
